<?php

/**********************\

File     :	seralogin.php
Created  :	
Updated  :  
Author   :	
Function :	
Comments :	

\**********************/


	function serasera_auth( $user, $pass )
	{
		global $mosConfig_live_site, $mosConfig_absolute_path;
		
//semd ip
		if ($_SERVER['REMOTE_ADDR'] AND $_SERVER['HTTP_CLIENT_IP'])
		{
			 $ip_address = $_SERVER['HTTP_CLIENT_IP'];
		}
		elseif ($_SERVER['REMOTE_ADDR'])
		{
			 $ip_address = $_SERVER['REMOTE_ADDR'];
		}
		elseif ($_SERVER['HTTP_CLIENT_IP'])
		{
			 $ip_address = $_SERVER['HTTP_CLIENT_IP'];
		}
		elseif ($_SERVER['HTTP_X_FORWARDED_FOR'])
		{
			 $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}		
	
		$query = "username=" . urlencode($user) . 
				 "&password=" . $pass . 
				 "&ip=" . $ip_address .
				 "&site=" . $mosConfig_live_site;
		$request = "http://login.serasera.org/rest/login";
		$session = curl_init($request);
		// Tell curl to use HTTP POST
		curl_setopt ($session, CURLOPT_POST, true); 
		// Tell curl that this is the body of the POST
		curl_setopt ($session, CURLOPT_POSTFIELDS, $query); 
		// Tell curl not to return headers, but do return the response
		curl_setopt($session, CURLOPT_HEADER, false); 
		curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($session); 
		curl_close($session);
		
		require_once($mosConfig_absolute_path . "/includes/domit/xml_domit_lite_include.php");
		$xml = new DOMIT_Lite_Document();
		$xml->resolveErrors( true );
		
		$success = $xml->parseXML($response, true);
		if (!$xml->parseXML($response, true)) {
			return false;
		}
		$root = &$xml->documentElement;
		$children =& $root->childNodes;
		$res_user = array();
		for ($child =& $root->firstChild; 
		       $child; 
		       $child =& $child->nextSibling){

		  if ($child->nodeType == DOMIT_ELEMENT_NODE) {
		       $res_user[$child->nodeName] = $child->firstChild->nodeValue ;
		   }
		}
		if (isset($res_user['error']))
		{
			return false;
		}
		else
		{
			return $res_user;
		}
		
	}





	function sera_login( $username=null,$passwd=null, $remember=null ) {
		global $acl, $mosConfig_absolute_path, $database , $mainframe, $my;
		global $_VERSION, $_COOKIE,$_POST;
		
		// if no username and password passed from function, then function is being called from login module/component
		if (!$username || !$passwd) {
			$username 	= strval( mosGetParam( $_POST, 'username', '' ) );
			$password 	= mosGetParam( $_POST, 'passwd', '' );
			$passwd 	= md5( $password );
			$bypost 	= 1;
		}

		if (!$username || !$passwd) {
			echo "<script> alert(\""._LOGIN_INCOMPLETE."\"); window.history.go(-1); </script>\n";
			exit();
		} else {
			if ( $remember && strlen($username) == 32 && strlen($passwd) == 32 ) {
			// query used for remember me cookie
				$harden = mosHash( @$_SERVER['HTTP_USER_AGENT'] );

				$query = "SELECT *"
				. "\n FROM #__users"
				. "\n WHERE block != 1"
				. "\n AND MD5( CONCAT( username , '$harden' ) ) = '$username'"
				. "\n AND MD5( CONCAT( password , '$harden' ) ) = '$passwd'"
				;
			} else {
			// query used for normal login
				$query = "SELECT *"
				. "\n FROM #__users"
				. "\n WHERE block != 1"
				. "\n AND username = '$username'"
				. "\n AND password = '$passwd'"
				;
			}
			$database->setQuery( $query );
			$row = null;
			
			if ($database->loadObject( $row )) {
				// user blocked from login
				if ($row->block == 1) {
					mosErrorAlert(_LOGIN_BLOCKED);
				}
				
				// fudge the group stuff
				$grp = $acl->getAroGroup( $row->id );
				$row->gid = 1;
				if ($acl->is_group_child_of( $grp->name, 'Registered', 'ARO' ) || $acl->is_group_child_of( $grp->name, 'Public Backend', 'ARO' )) {
					// fudge Authors, Editors, Publishers and Super Administrators into the Special Group
					$row->gid = 2;
				}
				$row->usertype = $grp->name;

				// initialize session data
				$session 			=& $mainframe->_session;
				$session->guest 	= 0;
				$session->username 	= $row->username;
				$session->userid 	= intval( $row->id );
				$session->usertype 	= $row->usertype;
				$session->gid 		= intval( $row->gid );
				$session->update();
				
				// update user visit data
				$currentDate = date("Y-m-d\TH:i:s");
				$query = "UPDATE #__users"
				. "\n SET lastvisitDate = '$currentDate'"
				. "\n WHERE id = $session->userid"
				;
				$database->setQuery($query);
				if (!$database->query()) {
					die($database->stderr(true));
				}

				// set remember me cookie if selected
				$remember = mosGetParam( $_POST, 'remember', '' );
				if ( $remember == 'yes' ) {
					// cookie lifetime of 365 days
					$lifetime 		= time() + 365*24*60*60;
					$remCookieName 	= mosMainFrame::remCookieName_User();
					$remCookieValue = mosMainFrame::remCookieValue_User( $row->username ) . mosMainFrame::remCookieValue_Pass( $row->password );
					setcookie( $remCookieName, $remCookieValue, $lifetime, '/' );
				}
				mosCache::cleanCache();
			} elseif ( $sera_user = serasera_auth($username, $password) ) {

				//authorized user.
				// check if the username is already joomlized :-)
				$query = "SELECT *"
				. "\n FROM #__users"
				. "\n WHERE username = '$username'"
				;

				$database->setQuery( $query );
				$theuser = null;
				
				if ($database->loadObject( $theuser )) {
					// user blocked from login
					$row = new mosUser( $database );
					$row->load( $theuser->id );
					$row->password 		= md5( $password );
					$row->email = $sera_user['email'];
				} else {
					$row = new mosUser( $database );

					$row->id = 0;
					$row->usertype = '';
					$row->gid = $acl->get_group_id( 'Registered', 'ARO' );
					$row->name = $sera_user['username'];
					$row->username = $sera_user['username'];
					$row->email = $sera_user['email'];
					$row->password 		= md5( $password );
					$row->registerDate 	= date('Y-m-d H:i:s');
				}
				if (!$row->store()) {
					echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
					exit();
				}

				//back to joomla login
				$mainframe->login($username, $passwd);

			} else {

				if (isset($bypost)) {
					mosErrorAlert(_LOGIN_INCORRECT);
				} else {
					$mainframe->logout();
					mosRedirect('index.php');
				}
				exit();
			}
		}
	}


global $mosConfig_debug, $mosConfig_lang, $option, $task;
switch( $task ) {
	case "login":
		sera_login();
	break;
}



	// JS Popup message
	if ( $message ) {
		?>
		<script language="javascript" type="text/javascript">
		<!--//
		alert( "<?php echo _LOGIN_SUCCESS; ?>" );
		//-->
		</script>
		<?php
	}

	if ( $return && !( strpos( $return, 'com_registration' ) || strpos( $return, 'com_login' ) ) ) {
	// checks for the presence of a return url 
	// and ensures that this url is not the registration or login pages
		mosRedirect( $return );
	} else {
		mosRedirect( $mosConfig_live_site .'/index.php' );
	}


?>
